// app/model/reconciliation_result_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DECIMAL, DATE, TEXT, ENUM } = app.Sequelize;

  const ReconciliationResult = app.model.define('reconciliationResult', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    salesOrderId: {
      type: INTEGER,
      allowNull: false,
      field: 'sales_order_id',
      comment: '销售订单ID'
    },
    bankTransactionId: {
      type: INTEGER,
      allowNull: false,
      field: 'bank_transaction_id',
      comment: '银行流水ID'
    },
    matchType: {
      type: ENUM('auto', 'manual'),
      allowNull: false,
      field: 'match_type',
      comment: '匹配类型'
    },
    matchConfidence: {
      type: DECIMAL(5, 2),
      field: 'match_confidence',
      comment: '匹配置信度(0-100)'
    },
    matchAlgorithm: {
      type: STRING(50),
      field: 'match_algorithm',
      comment: '匹配算法'
    },
    matchStatus: {
      type: ENUM('pending', 'confirmed', 'rejected'),
      defaultValue: 'pending',
      field: 'match_status',
      comment: '匹配状态'
    },
    matchedBy: {
      type: INTEGER,
      field: 'matched_by',
      comment: '匹配操作人'
    },
    matchedAt: {
      type: DATE,
      field: 'matched_at',
      comment: '匹配时间'
    },
    confirmedBy: {
      type: INTEGER,
      field: 'confirmed_by',
      comment: '确认操作人'
    },
    confirmedAt: {
      type: DATE,
      field: 'confirmed_at',
      comment: '确认时间'
    },
    notes: {
      type: TEXT,
      comment: '备注'
    }
  }, {
    tableName: 'reconciliation_results',
    timestamps: false
  });

  // 添加关联关系
  ReconciliationResult.associate = function() {
    // 对账结果与销售订单的关联
    if (app.model.SalesOrderModel) {
      ReconciliationResult.belongsTo(app.model.SalesOrderModel, {
        foreignKey: 'salesOrderId',
        as: 'salesOrder'
      });
    }

    // 对账结果与银行流水的关联
    if (app.model.BankTransactionModel) {
      ReconciliationResult.belongsTo(app.model.BankTransactionModel, {
        foreignKey: 'bankTransactionId',
        as: 'bankTransaction'
      });
    }

    // 对账结果与组织的关联
    if (app.model.OrganizationModel) {
      ReconciliationResult.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }
  };

  return ReconciliationResult;
};